package com.wang.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.wang.dao.IHandler;
import com.wang.domain.Homework;
import com.wang.domain.Student;

public class HomeworkDaoImpl{
	private static final String TABLE = "homework";
	private List<Homework> getStudentQuery(ResultSet resultlist) throws SQLException {
		List<Homework> arrayList = new ArrayList<Homework>();
		while(resultlist.next()){
			Homework homework = new Homework();
			homework.setId(resultlist.getLong("id"));
			homework.setUsername(resultlist.getString("username"));
			homework.setGroup(resultlist.getString("group"));
			homework.setCreatetime(resultlist.getString("createtime"));
			homework.setUpdatetime(resultlist.getString("updatetime"));
			arrayList.add(homework);
		}
		return arrayList;
	}
	public List<Homework> findAll() {
		IHandler<Homework> handler = (resultlist)->getStudentQuery(resultlist);
		String sql = "select h.*,s.username,s.group from "+TABLE+" as h left join student as s on s.id = h.student_id where h.createtime = '"+new SimpleDateFormat("yyyy-MM-DD").format(new Date())+"'";
		List<Homework> list = BaseDaoImpl.sqlQuery(sql, handler);
		return list;
	}
	public Integer add(String update,String create,Long student_id) {
		IHandler<Homework> handler = (resultlist)->getStudentQuery(resultlist);
		List<Homework> sqlQuery = BaseDaoImpl.sqlQuery("select h.*,s.username,s.group from "+TABLE+" as h left join student as s on s.id = h.student_id where h.createtime = '"+new SimpleDateFormat("yyyy-MM-DD").format(new Date())+"' and h.student_id =? ", handler,student_id);
		if(!sqlQuery.isEmpty())
			return BaseDaoImpl.sqlExecute("update "+TABLE+" set updatetime=? where createtime = '"+new SimpleDateFormat("yyyy-MM-DD").format(new Date())+"' and student_id =? ",update,student_id);
		return BaseDaoImpl.sqlExecute("insert into "+TABLE+" (updatetime,createtime,student_id) values (?,?,?)", update,create,student_id);
	}
}
